const app = getApp()
const config = app.globalData.config

Page({
  data: {
    currentStep: 1,
    activityName: '',
    activityDesc: '',
    activityDays: '',
    totalPeople: '',
    imagePath: '',
    activityTheme: '',
    teamCount: '',
    teamSize: '',
    dailyStartTime: '',
    dailyEndTime: '',
    tasks: [],
    countdownSeconds: 5,
    showPayment: false,
    showCompletion: false,
    activityData: null, // 存储完整的活动数据
    payAmount: 0
  },

  // 验证数字是否为正整数
  isPositiveInteger(value) {
    return /^[1-9]\d*$/.test(value);
  },

  // 计算时间差（分钟）
  calculateTimeDifference(startTime, endTime) {
    const start = new Date(`2000/01/01 ${startTime}:00`);
    const end = new Date(`2000/01/01 ${endTime}:00`);
    return Math.floor((end - start) / 1000 / 60);
  },

  // 验证第一页表单
  validateFirstPage() {
    // 暂时注释掉所有验证,方便测试
    return true;

    /* 原始验证代码
    const {
      activityName,
      activityDesc,
      activityDays,
      totalPeople,
      activityTheme,
      teamCount,
      teamSize,
      dailyStartTime,
      dailyEndTime,
      imagePath
    } = this.data;

    // 检查所有必填字段
    if (!activityName) {
      wx.showToast({
        title: '请输入活动名称',
        icon: 'none'
      });
      return false;
    }

    if (!activityDesc) {
      wx.showToast({
        title: '请输入活动描述',
        icon: 'none'
      });
      return false;
    }

    // 验证活动天数为正整数
    if (!activityDays || !this.isPositiveInteger(activityDays)) {
      wx.showToast({
        title: '活动天数必须为大于0的整数',
        icon: 'none'
      });
      return false;
    }

    // 验证总人数为正整数
    if (!totalPeople || !this.isPositiveInteger(totalPeople)) {
      wx.showToast({
        title: '总人数必须为大于0的整数',
        icon: 'none'
      });
      return false;
    }

    if (!activityTheme) {
      wx.showToast({
        title: '请输入活动主题',
        icon: 'none'
      });
      return false;
    }

    // 验证队伍数量为正整数
    if (!teamCount || !this.isPositiveInteger(teamCount)) {
      wx.showToast({
        title: '队伍数量必须为大于0的整数',
        icon: 'none'
      });
      return false;
    }

    // 验证每队人数为正整数
    if (!teamSize || !this.isPositiveInteger(teamSize)) {
      wx.showToast({
        title: '每队人数必须为大于0的整数',
        icon: 'none'
      });
      return false;
    }

    // 验证队伍容量是否满足总人数要求
    const totalCapacity = parseInt(teamCount) * parseInt(teamSize);
    if (totalCapacity < parseInt(totalPeople)) {
      wx.showToast({
        title: '队伍总容量必须不小于总人数',
        icon: 'none'
      });
      return false;
    }

    if (!dailyStartTime) {
      wx.showToast({
        title: '请选择每日开始时间',
        icon: 'none'
      });
      return false;
    }

    if (!dailyEndTime) {
      wx.showToast({
        title: '请选择每日结束时间',
        icon: 'none'
      });
      return false;
    }

    // 验证开始时间和结束时间
    const timeDiff = this.calculateTimeDifference(dailyStartTime, dailyEndTime);
    if (timeDiff <= 0) {
      wx.showToast({
        title: '结束时间必须大于开始时间',
        icon: 'none'
      });
      return false;
    }

    if (!imagePath) {
      wx.showToast({
        title: '请上传活动图片',
        icon: 'none'
      });
      return false;
    }

    return true;
    */
  },

  // 验证第二页表单
  validateSecondPage() {
    // 暂时注释掉验证,方便测试
    return true;

    /* 原始验证代码
    if (this.data.tasks.length === 0) {
      wx.showToast({
        title: '请至少添加一个任务',
        icon: 'none'
      });
      return false;
    }
    return true;
    */
  },

  // 保存第一步数据
  saveFirstStepData() {
    const userInfo = wx.getStorageSync('userInfo') || {};
    const activityData = {
      activityName: this.data.activityName,
      activityDesc: this.data.activityDesc,
      activityDays: Number(this.data.activityDays),
      totalPeople: Number(this.data.totalPeople),
      imagePath: this.data.imagePath,
      activityTheme: this.data.activityTheme,
      teamCount: Number(this.data.teamCount),
      teamSize: Number(this.data.teamSize),
      dailyStartTime: this.data.dailyStartTime,
      dailyEndTime: this.data.dailyEndTime,
      coachId: userInfo.coachId || '',
      activityStatus: this.data.activityStatus || '0',
      createTime: '', // 可由后端生成
      updateTime: '', // 可由后端生成
      tasks: (this.data.tasks || []).map(task => ({
        taskName: task.taskName,
        taskDesc: task.taskDesc,
        taskLevel: task.taskLevel,
        taskType: task.taskType,
        imagePath: task.imagePath,
        activityId: task.activityId // 如果有
      }))
    };
    wx.setStorageSync('tempActivityData', activityData);
    this.setData({
      activityData: activityData
    });
  },

  // 跳转到添加任务页面
  navigateToAddTask() {
    wx.navigateTo({
      url: '/pages/coach/taskEdit/taskEdit',
      events: {
        // 监听添加任务页面返回的数据
        addTask: (task) => {
          this.addTask(task);
        }
      }
    });
  },

  // 添加任务
  addTask(task) {
    try {
      const activityData = this.data.activityData || wx.getStorageSync('tempActivityData');
      if (!activityData) {
        console.error('活动数据不存在');
        return;
      }

      // 确保tasks数组存在
      if (!activityData.tasks) {
        activityData.tasks = [];
      }

      // 直接push传递过来的task对象
      activityData.tasks.push(task);
      
      // 更新本地存储
      wx.setStorageSync('tempActivityData', activityData);
      
      // 更新页面数据
      this.setData({
        activityData: activityData,
        tasks: activityData.tasks
      });

      wx.showToast({
        title: '添加成功',
        icon: 'success'
      });
    } catch (error) {
      console.error('添加任务失败:', error);
      wx.showToast({
        title: '添加失败',
        icon: 'none'
      });
    }
  },

  // 编辑任务
  editTask(e) {
    try {
      const index = e.currentTarget.dataset.index;
      const task = this.data.tasks[index];
      
      // 跳转到任务编辑页面
      wx.navigateTo({
        url: `/pages/coach/taskEdit/taskEdit?task=${JSON.stringify(task)}&index=${index}`,
        events: {
          // 监听编辑页面返回的数据
          editTask: (data) => {
            const activityData = this.data.activityData;
            activityData.tasks[index] = data;
            
            // 更新本地存储和页面数据
            wx.setStorageSync('tempActivityData', activityData);
            this.setData({
              activityData: activityData,
              tasks: activityData.tasks
            });
          }
        }
      });
    } catch (error) {
      console.error('编辑任务失败:', error);
      wx.showToast({
        title: '编辑失败',
        icon: 'none'
      });
    }
  },

  // 删除任务
  deleteTask(e) {
    try {
      const index = e.currentTarget.dataset.index;
      const activityData = this.data.activityData;
      
      wx.showModal({
        title: '确认删除',
        content: '确定要删除这个任务吗？',
        success: (res) => {
          if (res.confirm) {
            activityData.tasks.splice(index, 1);
            
            // 更新本地存储和页面数据
            wx.setStorageSync('tempActivityData', activityData);
            this.setData({
              activityData: activityData,
              tasks: activityData.tasks
            });

            wx.showToast({
              title: '删除成功',
              icon: 'success'
            });
          }
        }
      });
    } catch (error) {
      console.error('删除任务失败:', error);
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      });
    }
  },

  // 下一步
  nextStep() {
    if (this.data.currentStep === 1) {
      if (this.validateFirstPage()) {
        // 保存第一步数据
        this.saveFirstStepData();
        this.setData({
          currentStep: 2
        });
      }
    } else if (this.data.currentStep === 2) {
      console.info(this.data.activityData.tasks)
      // 请求后台获取金额
      wx.request({
        url: getApp().globalData.config.baseUrl[getApp().globalData.config.env] + config.apiPath.activity.dealcalcAmount,
        method: 'POST',
        header: {
          'Cookie': wx.getStorageSync('cookies'),
          'Content-Type': 'application/json'
        },
        data: this.data.activityData,
        success: (res) => {
          console.info(res)
          if (res.data && res.data.data.price) {
            this.setData({
              payAmount: res.data.data.price,
              currentStep: 3,
              showPayment: true
            });
          } else {
            wx.showToast({ title: '获取支付金额失败', icon: 'none' });
          }
        },
        fail: () => {
          wx.showToast({ title: '网络错误', icon: 'none' });
        }
      });
    } else if (this.data.currentStep === 3) {
      if (this.validateSecondPage()) {
        this.setData({
          currentStep: 4,
          showPayment: true
        });
      }
    }
  },

  // 页面加载时检查是否有暂存数据
  onLoad() {
    try {
      const tempData = wx.getStorageSync('tempActivityData');
      if (tempData) {
        this.setData({
          activityData: tempData,
          activityName: tempData.activityName,
          activityDesc: tempData.activityDesc,
          activityDays: tempData.activityDays,
          totalPeople: tempData.totalPeople,
          imagePath: tempData.imagePath,
          activityTheme: tempData.activityTheme,
          teamCount: tempData.teamCount,
          teamSize: tempData.teamSize,
          dailyStartTime: tempData.dailyStartTime,
          dailyEndTime: tempData.dailyEndTime,
          tasks: tempData.tasks || []
        });
      }
    } catch (error) {
      console.error('加载暂存数据失败:', error);
    }
  },

  // 页面卸载时清理数据
  onUnload() {
    try {
      // 如果完成了所有步骤,清理暂存数据
      if (this.data.showCompletion) {
        wx.removeStorageSync('tempActivityData');
      }
    } catch (error) {
      console.error('清理数据失败:', error);
    }
  },

  // 支付成功回调
  onPaymentSuccess() {
    this.setData({
      showPayment: false,
      showCompletion: true
    });
    this.startCountdown();
  },

  // 开始倒计时
  startCountdown() {
    const timer = setInterval(() => {
      if (this.data.countdownSeconds > 0) {
        this.setData({
          countdownSeconds: this.data.countdownSeconds - 1
        });
      } else {
        clearInterval(timer);
        wx.switchTab({
          url: '/pages/coach/activityList/activityList'
        });
      }
    }, 1000);
  },

  onNameInput(e) {
    this.setData({
      activityName: e.detail.value
    })
  },

  onDescInput(e) {
    this.setData({
      activityDesc: e.detail.value
    })
  },

  onDaysInput(e) {
    this.setData({
      activityDays: e.detail.value
    })
  },

  onTotalPeopleInput(e) {
    this.setData({
      totalPeople: e.detail.value
    })
  },

  onThemeInput(e) {
    this.setData({
      activityTheme: e.detail.value
    })
  },

  onTeamCountInput(e) {
    this.setData({
      teamCount: e.detail.value
    })
  },

  onTeamSizeInput(e) {
    this.setData({
      teamSize: e.detail.value
    })
  },

  onStartTimeChange(e) {
    this.setData({
      dailyStartTime: e.detail.value
    })
  },

  onEndTimeChange(e) {
    this.setData({
      dailyEndTime: e.detail.value
    })
  },

  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0]
        this.uploadImage(tempFilePath)
      }
    })
  },

  uploadImage(tempFilePath) {
    wx.showLoading({
      title: '上传中...',
    })

    // 获取存储的cookies
    const cookies = wx.getStorageSync('cookies')
    if (!cookies) {
      wx.hideLoading()
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    // 上传图片到服务器
    wx.uploadFile({
      url: config.baseUrl[config.env] + config.apiPath.upload.image,
      filePath: tempFilePath,
      name: 'file',
      header: {
        'Cookie': cookies
      },
      success: (res) => {
        const data = JSON.parse(res.data)
        if (data.errorCode === '000000') {
          this.setData({
            imagePath: data.data.url
          })
        } else {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },
}) 